var util = require("../../utils/util");
var config = require("../../config");

var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置
//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    tabs: [
      "读后感",
      "借阅轨迹"
    ],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,

    userInfo: {},
    book: {},
    applied: false,
    owner: {},
    notes: [],
    histories: []
  },
  onLoad: function (options) {
    var that = this;
    var book_id = options.id;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });

    wx.request({
      url: config.urls.onebook,
      data: {
        id: book_id
      },
      success: function (res) {
        if (res.data.success) {
          console.log(res)
          var book = res.data.book;
          that.formatData(book);
          that.setData({
            book: book
          });
          wx.request({
            url: config.urls.user_one,
            data: {
              id: book.owner
            },
            success: function (res) {
              if (res.data.success) {
                var user = res.data.user;
                console.log(user)
                that.setData({
                  owner: user
                });
              }
              else {
                console.log("no this user info: ", book.owner);
              }
            }
          });
        }
        else {
          console.log("no this book info: ", book_id);
        }
      }
    });

    that.setData({
      userInfo: app.globalData.userInfo
    });

    if (that.data.userInfo.id) {
      // 获取是否申请过的信息
      wx.request({
        url: config.urls.one_apply,
        data: {
          my_id: that.data.userInfo.id,
          book_id: book_id
        },
        success: function (res) {
          if (res.data.success) {
            that.setData({
              applied: true
            });
          }
          else {
            console.log("no this book apply info");
          }
        }
      });
    }

    // 获取读后感
    wx.request({
      url: config.urls.onebook_notes,
      data: {
        book_id: book_id,
        ps: 10,
        pn: 0
      },
      success: function (res) {
        if (res.data.success) {
          that.formatData2(res.data.notes);
          that.setData({
            notes: res.data.notes
          });
        }
        else {
          console.log("no this book notes");
        }
      }
    });

    // 获取借阅轨迹
    wx.request({
      url: config.urls.find_borrow_history,
      data: {
        book_id: book_id,
        ps:20,
        pn:0
      },
      success: function (res) {
        if (res.data.success) {
          console.log(res)
          that.formatData3(res.data.history);
          that.setData({
            histories: res.data.history
          });
         }
        else {
          console.log("no this book history");
        }
      }
    });

  },

  bookApply: function (e) {
    var that = this;
    var userInfo = that.data.userInfo;
    if (!userInfo.id) {
      // login first
      wx.showModal({
        title: '请先登录',
        content: '你尚未登录，不能借书，请先登录！',
        showCancel: false,
        success: function (res) {
          //
          wx.switchTab({
            url: '/pages/me/me',
          }); 
        }
      });

      return;
    }

    // 点了后，弹出确认，申请借这本书
    // 要弹出框提示确认下架
    wx.showModal({
      title: '确认申请',
      content: '请确认是否借阅本书',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          var book = that.data.book;


          wx.request({
            url: config.urls.book_apply_new,
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              book_id: book.id,
              book_name: book.name,
              book_pic: book.pic,
              cur_user_id: book.owner,
              cur_user_name: book.owner_name,
              applier_id: userInfo.id,
              applier_name: userInfo.nickname
            },
            success: function (res) {
              if (res.data.success) {
                wx.showToast({
                  title: '申请成功',
                  icon: 'success',
                  duration: 1000
                })
                that.setData({
                  applied: true
                });
              }
              else {
                wx.showToast({
                  title: '申请失败',
                  icon: 'loading',
                  duration: 1000
                })
                console.log("Book apply failed.");
              }
            }
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  tabClick: function (e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
  },
  cancel: function (e) {
    wx.navigateBack({
      delta: 1
    })
  },
  takeNote: function (e) {
    var that = this;
    wx.navigateTo({
      url: '/pages/takenote/takenote?book_id=' + that.data.book.id
    })
  },
  formatData: function (data) {
    var item = data;
    item.putaway_time = util.fds(item.putaway_time);
    if (item.borrower_name == "") {
      item.borrower_name = "无";
    }
    if (item.borrow_time == -1) {
      item.borrow_time = "无";
    }
    else {
      item.borrow_time = util.fds(item.borrow_time);
    }
  },
  formatData2: function (data) {
    for (var i = 0; i < data.length; i++) {
      var item = data[i];
      item.created_time = util.fds(item.created_time);
    }
  },

  formatData3:function (data){
    for (var i = 0; i < data.length; i++) {
      var item = data[i];
      item.action_time = util.fds(item.action_time);
    }
  },

  onShareAppMessage: function (res) {
    var that = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: "《" + that.data.book.name + "》正在共享中~",
      path: that.route + "?id=" + that.data.book.id,
      success: function (res) {
        // 转发成功
        console.log(res.target)
      },
      fail: function (res) {
        // 转发失败
        console.log(res.target)
      }
    }
  },
  newChat:function () {
    var that = this;
    wx.request({
      url: config.urls.newChatsession,
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        user_a: that.data.userInfo.id,
        user_a_name: that.data.userInfo.nickname,
        user_a_avatar:"",
        user_b: that.data.owner.id,
        user_b_name: that.data.owner.nickname,
        user_b_avatar:""
      },
      success: function (res) {
        if (res.data.success) {
          console.log(res);
          var user_opposite = that.data.userInfo.id == res.data.chat_session.user_a ? res.data.chat_session.user_b : res.data.chat_session.user_a;
          var user_opposite_name = that.data.userInfo.id == res.data.chat_session.user_a ? res.data.chat_session.user_b_name : res.data.chat_session.user_a_name;
          wx.navigateTo({
            url: '/pages/chatmsg/chatmsg?chat_session_id=' + res.data.chat_session.id + '&user_opposite=' + user_opposite + "&user_opposite_name=" + user_opposite_name
          })
        }
        else {
          console.log("no this book notes");
        }
      }
    });
  },
  newChat2: function () {
    var that = this;
    wx.request({
      url: config.urls.newChatsession,
      method: "POST",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        user_a: that.data.userInfo.id,
        user_a_name: that.data.userInfo.nickname,
        user_a_avatar: "",
        user_b: that.data.book.borrower,
        user_b_name: that.data.book.borrower_name,
        user_b_avatar: ""
      },
      success: function (res) {
        if (res.data.success) {
          console.log(res);
          var user_opposite = that.data.userInfo.id == res.data.chat_session.user_a ? res.data.chat_session.user_b : res.data.chat_session.user_a;
          var user_opposite_name = that.data.userInfo.id == res.data.chat_session.user_a ? res.data.chat_session.user_b_name : res.data.chat_session.user_a_name;
          wx.navigateTo({
            url: '/pages/chatmsg/chatmsg?chat_session_id=' + res.data.chat_session.id + '&user_opposite=' + user_opposite + "&user_opposite_name=" + user_opposite_name
          })
        }
        else {
          console.log("no this book notes");
        }
      }
    });
  },
  show_detail:function(){
    var that = this;
    wx.navigateTo({
      url: '/pages/detail/detail?id='+ that.data.owner.id,
    })
  }
})


